import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

class WebSocketClient {
  constructor() {
    this.baseWs = null; // 基础连接
    this.videoWs = null; // 视频连接
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectTimeout = 3000;
    this.commentHandlers = new Set();
    this.danmakuHandlers = new Set();
    this.currentVideoId = null;
    
    // 在构造函数中直接检查登录状态并连接
    this.checkAndConnect();
  }

  // 检查登录状态并建立基础连接
  checkAndConnect() {
    const token = localStorage.getItem('token');
    if (token) {
      this.connectBase();
    } else {
      console.log('用户未登录，不建立WebSocket连接');
    }
  }

  // 建立基础WebSocket连接
  connectBase() {
    const token = localStorage.getItem('token');
    if (!token) {
      console.error('WebSocket连接失败: 未找到token');
      return;
    }

    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const baseUrl = import.meta.env.VITE_WS_URL || 'localhost:8080';
    const wsUrl = `${wsProtocol}//${baseUrl}/websocket/comment/base?token=Bearer ${token}`;
    
    console.log('正在连接基础WebSocket:', wsUrl);
    
    this.baseWs = new WebSocket(wsUrl);

    this.baseWs.onopen = () => {
      this.reconnectAttempts = 0;
      console.log('%c✅ 基础WebSocket连接成功!', 'color: green; font-weight: bold');
    };

    this.baseWs.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        console.log('%c📨 收到新消息:', 'color: blue; font-weight: bold', data);

        // 如果消息本身就是评论对象（没有type字段）
        if (!data.type && data.videoId) {
          console.log('收到评论消息:', data);
          this.commentHandlers.forEach(handler => handler(data));
          return;
        }

        // 如果消息带有type字段
        if (data.type === 'comment') {
          console.log('收到评论消息:', data.data);
          this.commentHandlers.forEach(handler => handler(data.data));
        } else if (data.type === 'danmaku') {
          console.log('收到弹幕消息:', data.data);
          this.danmakuHandlers.forEach(handler => handler(data.data));
        }
      } catch (error) {
        console.error('WebSocket消息处理失败:', error);
        // 尝试作为纯文本处理
        try {
          const data = { content: event.data };
          this.commentHandlers.forEach(handler => handler(data));
        } catch (e) {
          console.error('消息处理完全失败:', e);
        }
      }
    };

    this.baseWs.onclose = (event) => {
      console.log('%c❌ 基础WebSocket连接关闭', 'color: orange; font-weight: bold', {
        状态: 'Closed',
        关闭代码: event.code,
        关闭原因: event.reason,
        时间: new Date().toLocaleString()
      });
      
      if (event.code !== 1000) {
        this.reconnectBase();
      }
    };

    this.baseWs.onerror = (error) => {
      console.log('%c⚠️ WebSocket错误', 'color: red; font-weight: bold', {
        状态: 'Error',
        错误信息: error,
        时间: new Date().toLocaleString()
      });
    };
  }

  // 连接到特定视频的WebSocket
  connectToVideo(videoId) {
    if (!videoId) {
      console.error('视频ID不能为空');
      return;
    }

    if (this.currentVideoId === videoId && this.videoWs?.readyState === WebSocket.OPEN) {
      console.log('已经连接到该视频的WebSocket，无需重新连接');
      return;
    }

    const token = localStorage.getItem('token');
    if (!token) {
      console.error('WebSocket连接失败: 未找到token');
      return;
    }

    // 关闭现有的视频连接
    if (this.videoWs) {
      this.videoWs.close();
    }

    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const baseUrl = import.meta.env.VITE_WS_URL || 'localhost:8080';
    const wsUrl = `${wsProtocol}//${baseUrl}/websocket/comment/${videoId}?token=Bearer ${token}`;
    
    console.log('正在连接视频WebSocket:', wsUrl);
    
    this.videoWs = new WebSocket(wsUrl);
    this.currentVideoId = videoId;

    this.videoWs.onopen = () => {
      console.log('%c✅ 视频WebSocket连接成功!', 'color: green; font-weight: bold', {
        状态: 'Connected',
        视频ID: videoId,
        连接时间: new Date().toLocaleString()
      });
    };

    this.videoWs.onclose = (event) => {
      if (event.code !== 1000) {
        this.reconnectVideo(videoId);
      }
    };
  }

  // 基础连接重连
  reconnectBase() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) return;
    setTimeout(() => {
      this.reconnectAttempts++;
      this.connectBase();
    }, this.reconnectTimeout);
  }

  // 视频连接重连
  reconnectVideo(videoId) {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) return;
    setTimeout(() => {
      this.reconnectAttempts++;
      this.connectToVideo(videoId);
    }, this.reconnectTimeout);
  }

  // 关闭所有连接
  close() {
    if (this.baseWs) {
      this.baseWs.close(1000, "Normal closure");
      this.baseWs = null;
    }
    if (this.videoWs) {
      this.videoWs.close(1000, "Normal closure");
      this.videoWs = null;
      this.currentVideoId = null;
    }
  }

  // 检查连接状态
  isConnected() {
    return (
      this.baseWs?.readyState === WebSocket.OPEN ||
      this.videoWs?.readyState === WebSocket.OPEN
    );
  }

  // 处理器方法保持不变
  addCommentHandler(handler) {
    this.commentHandlers.add(handler);
  }

  removeCommentHandler(handler) {
    this.commentHandlers.delete(handler);
  }

  addDanmakuHandler(handler) {
    this.danmakuHandlers.add(handler);
  }

  removeDanmakuHandler(handler) {
    this.danmakuHandlers.delete(handler);
  }
}

const wsClient = new WebSocketClient();
export const reconnectWebSocket = () => wsClient.checkAndConnect();
export default wsClient; 